<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use iflow\Response;

class oauthConfigModel extends QueryModel
{

    protected $table = "oauth_config_table";

    public function getConfigList(string $configName = ""): Response
    {
        $query = $this->where([
            'status' => 1
        ]);
        if ($configName !== "") {
            $query -> whereLike('config_name', "%{$configName}%");
        }

        return $this->paginateQuery($query);
    }

    /**
     * 添加配置
     * @param string $configName
     * @param array $config
     * @return Response
     */
    public function addConfig(string $configName, array $config): Response {

        if ($this->where([
            'config_name' => $configName,
        ]) -> findOrEmpty() -> isExists()) return message() -> parameter_error('配置名称不能重复');

        if (!empty($config['is_default']) && $config['is_default'] !== 0) {
            $this->updateInfo([ 'is_default' => 0 ], [ 'is_default' => 1, 'config_type' => $config['config_type'] ]);
        }

        $data = self::create([
            'config_name' => $configName,
            'config_info' => json_encode($config),
            'config_type' => $config['config_type'],
            'is_default' => $config['is_default'] ?? 0
        ]) -> toArray();

        if ($data) {
            $data['config_id'] = $data['id'];
            return message() -> success('创建成功', $data);
        }
        return message() -> update_failed('创建失败请重试');
    }

    public function updateConfig(int $config_id, string $configName, array $config): Response {

        if (!empty($config['is_default']) && $config['is_default'] !== 0) {
            $this->updateInfo([ 'is_default' => 0 ], [ 'is_default' => 1, 'config_type' => $config['config_type'] ]);
        }

        return $this->updateInfo([
            'config_name' => $configName,
            'config_info' => json_encode($config),
            'is_default' => $config['is_default'] ?? 0
        ], [ 'config_id' => $config_id ]);
    }

    /**
     * 删除配置
     * @param int $config_id
     * @return Response
     */
    public function deleteConfig(int $config_id): Response {
        return $this->deleteData([ 'config_id' => $config_id ]);
    }
}